import {invertTree} from "@/utils/common";
import {RouteRecordRaw} from "vue-router";

/**
 * @param tree 路由树
 * @return temp 格式化后的路由对象
 * */
const recursiveRoutes = (tree: any) => {
    return tree.map((node: any) => {
        let temp: RouteRecordRaw = node
        if (node.component) {
            temp.component = loadView(node.component)
        }
        if (node.children?.length > 0) {
            recursiveRoutes(node.children)
        }
        return temp
    })
}
//页面路由 动态加载
const loadView = (view: string) => {
    return () => import(`@/views/${view}`)
}

/**
 * 添加路由
 * @param router
 * */
const insertRoutes = (router: any, store: any) => {
    store.commit("GET_ROUTES")
    if (store.getters.routes && store.getters.routes.length > 0) {
        let list = invertTree(store.getters.routes, "id", "pid", "children")
        recursiveRoutes(list)
        list.forEach(item => {
            router.addRoute(item)
        })
        //最后添加404页面，
        router.addRoute({
            path: "/:pathMatch(.*)*",
            name: "404",
            meta: {
                isMenu: false,
                tittle: "404",
                icon: "Sunrise"
            },
            component: () => import("../views/error/404.vue")
        })
    }

}
/**
 * 清除动态加载的路由
 * @param router
 * */
const clearRoutes = (router: any, store: any) => {
    store.commit("GET_ROUTES")
    if (store.getters.routes && store.getters.routes.length > 0) {
        store.getters.routes.forEach((item: any) => {
            router.removeRoute(item.name)
        })
    }
}




export {
    insertRoutes,
    clearRoutes
}

